<?php
class Tag extends AppModel {

	var $name = 'Tag';
    var $primaryKey = 'tag_id';
    var $hasAndBelongsToMany = array('Post');

    /**
     * Checking whether tag is exist or not
     * usage in : Post Controller -> function addTag()
     */
    function checkTagExist($tag){
        $this->recursive = -1;
        $result = $this->find('first',array(
            'fields'=>'Tag.tag_id',
            'conditions'=>array('AND'=>array('Tag.name'=>$tag,'Tag.status'=>'1'))));

        return $result;
    }

    /**
     * Saving tag
     * usage in : Post Controller -> function addTag()
     */
    function saveTags($tags = array()) {
        $this->recursive = -1;
        foreach($tags as $tag) {
            $status = $this->checkTagExist($tag);
            if(!is_array($status)) {
                $this->create();
                $data['Tag']['name']= $tag;
                $data['Tag']['slug']= Inflector::slug($tag);
                $this->save($data);
            }
        }
    }

    /**
     * Get tag id by $tags
     * usage in : Post Controller -> function addTag()
     */
    function getTagsId($tags = array()){
        $this->recursive = -1;
        foreach($tags as $tag=>$key) {
            $id = $this->find('first',array(
            'fields'=>'Tag.tag_id',
            'conditions'=>array('AND'=>array('Tag.name'=>$key,'Tag.status'=>'1'))
                ));

            $tags[$tag]=$id['Tag']['tag_id'];												// replacing tag name value with id
        }

        return $tags;
    }

   /**
    * Updating counter for post_count +1
    * usage in : Post Controller -> function addTag()
    */
    public function updateCounter($tags = array()){
        foreach($tags as $value){
            $count = $this->find('first',array('conditions'=>array('Tag.tag_id'=>$value),'field'=>'Tag.post_count'));
            $newCount = $count['Tag']['post_count'] + 1;
            $this->id = $value;
            $this->saveField('post_count',$newCount);
        }
    }


}
?>
